import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  permissions: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // 用户登陆
  login({ commit }, userInfo) {
    // 从userinfo里面取出username、password
    const { username, password, code } = userInfo
    // 进行发送请求 地狱回调
    return new Promise((resolve, reject) => {
      // 获取后端访问登陆接口发送http请求
      login({ username: username.trim(), password: password, code: code }).then(response => {
        // 获取到返回值
        const { token } = response
        // 设置token到全局变量区域 vuex
        commit('SET_TOKEN', token)
        // 存储到权限工具当中
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        // 获取参数
        const { username, picture, roles, permission, introduction } = response

        if (!username) {
          reject('用户未登录，请登录')
        }

        // 用户角色
        commit('SET_ROLES', roles)
        // 用户名称
        commit('SET_NAME', username)
        // 用户头像
        commit('SET_AVATAR', picture)
        // 用户权限
        commit('SET_PERMISSIONS', permission)
        // 用户详细信息
        commit('SET_INTRODUCTION', introduction)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出逻辑
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // 调用后端接口请求
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        // 移除token
        removeToken()

        // 重置路由
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
